//一般直接写在一个js文件中
layui.use(['element','form','laydate','upload','table'],function () {
    var form = layui.form,
        upload = layui.upload,
        table = layui.table,
        laydate = layui.laydate;
    laydate.render({
        elem: '#birthday' //指定元素
    });
    $("#avatarimg").on('click',function(){
        layer.open({
            title: '头像上传编辑器',
            type:2
            ,content: '/static/plugins/fullAvatarEditor/avatarupload.html'
            ,area: ['700px', '500px']
        });
    });

//省选择回调
    form.on('select(province)', function(data){
        var name = $(data.elem).find("option:selected").text();
        $("#provinceName").val(name);
        $("#provinceCode").val(data.value);
        $.ajax({
            url:"/city?pId="+data.value,
            type:'get',
            dataType:'json',
            success:function (rs) {
                if(rs){
                    $("#city").empty().append('<option value="">请选择市</option>');
                    $.each(rs,function(i,d){
                        $("#city").append('<option value="'+d.id+'">'+d.name+'</option>');
                    });
                    form.render('select'); //刷新select选择框渲染
                }
            }
        });
    });

    //市选择回调
    form.on('select(city)', function(data){
        var name = $(data.elem).find("option:selected").text();
        $("#cityName").val(name);
        $("#cityCode").val(data.value);
        $.ajax({
            url:"/area?pId="+data.value,
            type:'get',
            dataType:'json',
            success:function (rs) {
                if(rs){
                    $("#area").empty().append('<option value="">请选择区(县)</option>');
                    $.each(rs,function(i,d){
                        $("#area").append('<option value="'+d.id+'">'+d.name+'</option>');
                    });
                    form.render('select'); //刷新select选择框渲染
                }
            }
        });
    });

    //区选择回调
    form.on('select(area)', function(data){
        var name = $(data.elem).find("option:selected").text();
        $("#areaName").val(name);
        $("#areaCode").val(data.value);
        $.ajax({
            url:"/town?pId="+data.value,
            type:'get',
            dataType:'json',
            success:function (rs) {
                if(rs){
                    $("#town").empty().append('<option value="">请选择乡镇(街道)</option>');
                    $.each(rs,function(i,d){
                        $("#town").append('<option value="'+d.id+'">'+d.name+'</option>');
                    });
                    form.render('select'); //刷新select选择框渲染
                }
            }
        });
    });
    //镇选择回调
    form.on('select(town)', function(data){
        var name = $(data.elem).find("option:selected").text();
        $("#townName").val(name);
        $("#townCode").val(data.value);
        $.ajax({
            url:"/village?pId="+data.value,
            type:'get',
            dataType:'json',
            success:function (rs) {
                if(rs){
                    $("#village").empty().append('<option value="">请选择社区(村)</option>');
                    $.each(rs,function(i,d){
                        $("#village").append('<option value="'+d.id+'">'+d.name+'</option>');
                    });
                    form.render('select'); //刷新select选择框渲染
                }
            }
        });
    });


    //村选择回调
    form.on('select(village)', function(data){
        var name = $(data.elem).find("option:selected").text();
        $("#villageName").val(name);
        $("#villageCode").val(data.value);
    });


    //表单验证
    form.verify({
        only: function (value, item) { //value：表单的值、item：表单的DOM对象
            var flag = false;
            var idNo = $("#idNo").val();
            $.ajax({
                url:"/elderly/exists",
                data:{field:$(item).attr("name"),value:value,idNo:idNo},
                dataType:"json",
                async:false,
                type:"post",
                success:function(rs){
                    if(rs.code == 200 ){
                        flag = rs.data;
                    }
                }
            });
            if(flag){
                return $(item).data("label") + '已存在';
            }
        }
    });

//根据老人id查询联系人方法
    function getfolks(){
        $("#lxrtable tr").remove();
        var eldId=$("#id").val();
        $.ajax({
            url:"/enterElderly/getfolks",
            type:'post',
            dataType:'json',
            data: "id="+eldId,
            success:function(data){
                if(data.code == 200) {
                    var date = data.data;
                    var $html='';
                    $.each(date,function(i,d){
                        $html+='<tr><td>'+d.name+'</td><td>'+d.phone+'</td><td>'+d.relation+'</td><td>'+d.cardNo+'</td><td>'+d.address+'</td>' +
                            '<td><a href="javascript:void(0)" class="layui-btn folkeit" data-folkid="'+d.id+'">编辑</a><a href="javascript:void(0)" class="layui-btn layui-btn-danger folkdel" data-folkid="'+d.id+'">删除</a></td></tr>';
                    });
                    $("#lxrtable").append($html);
                }
            },
            error:function(e){
                console.log("加载失败");
            }
        });
    }
    //点击联系人
    $("#two").on('click',function () {
        getfolks();
    });
    var phone=/^1\d{10}$/;
    var cardNo=/(^\d{15}$)|(^\d{17}(x|X|\d)$)/;
    //新增联系人
    $("#lxradd").on('click',function () {
        layer.open({
            title:"添加联系人",
            content: $("#lxrhtml"),
            area: ['500px', '400px'],
            btn: ['保存','取消'],
            type:1,
            yes: function(index, layero){
                var eldId=$("#id").val();
                $("#folkElderId").val(eldId);
                var fromData = $("#lxrfrom").serialize();
                if ($("#folkName").val()=="" ){
                    layer.msg("联系人姓名不能为空",{time:1500});
                    return false;
                }
                if (!phone.test($("#folkPhone").val())){
                    layer.msg("请输入正确的联系人电话",{time:1500});
                    return false;
                }
                if ($("#folkCardNo").val()!=""){
                    if (!cardNo.test($("#folkCardNo").val())){
                        layer.msg("请输入正确的身份证号",{time:1500});
                        return false;
                    }
                }
                $.ajax({
                    url:"/enterElderly/savefolk",
                    type:'post',
                    dataType:'json',
                    data: fromData,
                    success:function(msg){
                        if(msg.code == 200) {
                            layer.close(index);
                            getfolks();
                            $("#lxrfrom")[0].reset();
                        }
                    },
                    error:function(e){
                        console.log("加载失败");
                    }
                });
            }
        });
    });
    //编辑联系人
    $("#lxrtable").on('click','.folkeit',function () {
        var id=$(this).data("folkid");
        $.ajax({
            url:"/enterElderly/getFolkById",
            type:'post',
            dataType:'json',
            data: "id="+id,
            success:function(msg){
                var date=msg.data;
                if(msg.code == 200) {
                    layer.open({
                        title:"编辑联系人",
                        content: $("#lxrhtml"),
                        area: ['500px', '400px'],
                        btn: ['保存','取消'],
                        type:1,
                        success: function(layero, index){
                            $("#folkName").val(date.name);
                            $("#folkElderId").val(date.elderlyId);
                            $("#folkCardNo").val(date.cardNo);
                            $("#folkRelation").val(date.relation);
                            $("#folkPhone").val(date.phone);
                            $("#folkAddress").val(date.address);
                        },
                        yes: function(index, layero){
                                    var fromData = $("#lxrfrom").serialize()+"&id="+id;
                                    if ($("#folkName").val()=="" ){
                                        layer.msg("联系人姓名不能为空",{time:1500});
                                        return false;
                                    }
                                    if (!phone.test($("#folkPhone").val())){
                                        layer.msg("请输入正确的联系人电话",{time:1500});
                                        return false;
                                    }
                                    if ($("#folkCardNo").val()!=""){
                                        if (!cardNo.test($("#folkCardNo").val())){
                                            layer.msg("请输入正确的身份证号",{time:1500});
                                            return false;
                                        }
                                    }
                                    $.ajax({
                                        url:"/enterElderly/updatefolk",
                                        type:'post',
                                        dataType:'json',
                                        data: fromData,
                                        success:function(msg){
                                            if(msg.code == 200) {
                                                layer.close(index);
                                                getfolks();
                                                $("#lxrfrom")[0].reset();
                                            }
                                        },
                                        error:function(e){
                                            console.log("加载失败");
                                        }
                                    });
                        }
                    });
                }
            },
            error:function(e){
                console.log("加载失败");
            }
        });
    })
    //删除联系人
    $("#lxrtable").on('click','.folkdel',function () {
        var id=$(this).data("folkid");
        $.ajax({
            url:"/enterElderly/delfolk",
            type:'post',
            dataType:'json',
            data: "id="+id,
            success:function(msg){
                if(msg.code == 200) {
                    getfolks();
                }
            },
            error:function(e){
                console.log("加载失败");
            }
        });
    })

    //保存老人基本信息
    $("#jbxxbtn").on('click',function () {
        var eldId=$("#id").val();
        var fromData = $("#jbxxform").serialize()+"&id="+eldId;
        $.ajax({
            url:"/enterElderly/update",
            type:'post',
            dataType:'json',
            data: fromData,
            success:function(msg){
                if(msg.code == 200) {
                    layer.msg("保存成功", {time: 1000},function () {
                        location.href = "/enterElderly/edit?id="+eldId;
                    });
                }
            },
            error:function(e){
                console.log("加载失败");
            }
        });
    })
    //保存老人健康信息
    $("#jkbtn").on('click',function () {
        var eldId=$("#id").val();
        var fromData = $("#jkform").serialize()+"&id="+eldId;
        $.ajax({
            url:"/enterElderly/update",
            type:'post',
            dataType:'json',
            data: fromData,
            success:function(msg){
                if(msg.code == 200) {
                    layer.msg("保存成功", {time: 1000},function () {
                        // location.href = "/enterElderly/edit?id="+eldId;
                    });
                }
            },
            error:function(e){
                console.log("加载失败");
            }
        });
    })
    // 上传身份证
    upload.render({
        elem: '#lazlone'
        ,url: '/storage/files/ul'
        ,field: 'file'
        ,accept:"images"
        ,acceptMime:"image/jpg,image/jpeg,image/png"
        ,size:5120
        ,done: function(res){
            if(res.code != 200){
                return layer.msg('上传失败');
            }
            $.ajax({
                url:"/elderlyPth/save",
                type:'POST',
                dataType:'JSON',
                data:{elderlyId:$("#id").val(),name:res.data.fileName,path:res.data.path,type:$("#lazlone").data("type")},
                success:function(rs){
                    if(rs.code == 200){
                        $("#lazlone").before('<div class="layui-upload-list" style="margin:0 10px 5px;">' +
                            '<img class="layui-upload-img" src="/storage/images/'+rs.data.path+'_120x120"/>' +
                            '<p class="file-nme" title="'+rs.data.name+'">'+ rs.data.name +'</p>' +
                            '<p class="msg-box"><a target="_blank" href="/storage/files/'+res.data.path+'" class="layui-btn layui-btn-normal layui-btn-xs">查看</a><a  href="/storage/files/dl/'+res.data.path+'" class="layui-btn layui-btn-normal  layui-btn-xs">下载</a><button  data-pthid="'+rs.data.id+'"  class="layui-btn layui-btn-normal  layui-btn-xs pthid" type="button">删除</button></p></div>');

                    }else {
                        layer.msg('上传失败');
                    }
                }
            });
        }
    });
    // 上传特困认定材料
    upload.render({
        elem: '#lazltwo'
        ,url: '/storage/files/ul'
        ,field: 'file'
        ,accept:"images"
        ,acceptMime:"image/jpg,image/jpeg,image/png"
        ,size:5120
        ,done: function(res){
            if(res.code != 200){
                return layer.msg('上传失败');
            }
            $.ajax({
                url:"/elderlyPth/save",
                type:'POST',
                dataType:'JSON',
                data:{elderlyId:$("#id").val(),name:res.data.fileName,path:res.data.path,type:$("#lazltwo").data("type")},
                success:function(rs){
                    if(rs.code == 200){
                        $("#lazltwo").before('<div class="layui-upload-list" style="margin:0 10px 5px;">' +
                            '<img class="layui-upload-img" src="/storage/images/'+rs.data.path+'_120x120"/>' +
                            '<p class="file-nme" title="'+rs.data.name+'">'+ rs.data.name +'</p>' +
                            '<p class="msg-box"><a target="_blank" href="/storage/files/'+res.data.path+'" class="layui-btn layui-btn-normal layui-btn-xs">查看</a><a  href="/storage/files/dl/'+res.data.path+'" class="layui-btn layui-btn-normal  layui-btn-xs">下载</a><button  href="/elderlyPth/delete?id='+rs.data.id+'" class="layui-btn layui-btn-normal  layui-btn-xs pthid" type="button">删除</button></p></div>');

                    }else {
                        layer.msg('上传失败');
                    }
                }
            });
        }
    });
    // 上传特困人员救助供养证
    upload.render({
        elem: '#lazlthree'
        ,url: '/storage/files/ul'
        ,field: 'file'
        ,accept:"images"
        ,acceptMime:"image/jpg,image/jpeg,image/png"
        ,size:5120
        ,done: function(res){
            if(res.code != 200){
                return layer.msg('上传失败');
            }
            $.ajax({
                url:"/elderlyPth/save",
                type:'POST',
                dataType:'JSON',
                data:{elderlyId:$("#id").val(),name:res.data.fileName,path:res.data.path,type:$("#lazlthree").data("type")},
                success:function(rs){
                    if(rs.code == 200){
                        $("#lazlthree").before('<div class="layui-upload-list" style="margin:0 10px 5px;">' +
                            '<img class="layui-upload-img" src="/storage/images/'+rs.data.path+'_120x120"/>' +
                            '<p class="file-nme" title="'+rs.data.name+'">'+ rs.data.name +'</p>' +
                            '<p class="msg-box"><a target="_blank" href="/storage/files/'+res.data.path+'" class="layui-btn layui-btn-normal layui-btn-xs">查看</a><a  href="/storage/files/dl/'+res.data.path+'" class="layui-btn layui-btn-normal  layui-btn-xs">下载</a><button  href="/elderlyPth/delete?id='+rs.data.id+'" class="layui-btn layui-btn-normal  layui-btn-xs pthid" type="button">删除</button></p></div>');

                    }else {
                        layer.msg('上传失败');
                    }
                }
            });
        }
    });
    // 上传医保卡
    upload.render({
        elem: '#lazlfour'
        ,url: '/storage/files/ul'
        ,field: 'file'
        ,accept:"images"
        ,acceptMime:"image/jpg,image/jpeg,image/png"
        ,size:5120
        ,done: function(res){
            if(res.code != 200){
                return layer.msg('上传失败');
            }
            $.ajax({
                url:"/elderlyPth/save",
                type:'POST',
                dataType:'JSON',
                data:{elderlyId:$("#id").val(),name:res.data.fileName,path:res.data.path,type:$("#lazlfour").data("type")},
                success:function(rs){
                    if(rs.code == 200){
                        $("#lazlfour").before('<div class="layui-upload-list" style="margin:0 10px 5px;">' +
                            '<img class="layui-upload-img" src="/storage/images/'+rs.data.path+'_120x120"/>' +
                            '<p class="file-nme" title="'+rs.data.name+'">'+ rs.data.name +'</p>' +
                            '<p class="msg-box"><a target="_blank" href="/storage/files/'+res.data.path+'" class="layui-btn layui-btn-normal layui-btn-xs">查看</a><a  href="/storage/files/dl/'+res.data.path+'" class="layui-btn layui-btn-normal  layui-btn-xs">下载</a><button  href="/elderlyPth/delete?id='+rs.data.id+'" class="layui-btn layui-btn-normal  layui-btn-xs pthid" type="button">删除</button></p></div>');

                    }else {
                        layer.msg('上传失败');
                    }
                }
            });
        }
    });
    // 上传残疾证
    upload.render({
        elem: '#lazlfive'
        ,url: '/storage/files/ul'
        ,field: 'file'
        ,accept:"images"
        ,acceptMime:"image/jpg,image/jpeg,image/png"
        ,size:5120
        ,done: function(res){
            if(res.code != 200){
                return layer.msg('上传失败');
            }
            $.ajax({
                url:"/elderlyPth/save",
                type:'POST',
                dataType:'JSON',
                data:{elderlyId:$("#id").val(),name:res.data.fileName,path:res.data.path,type:$("#lazlfive").data("type")},
                success:function(rs){
                    if(rs.code == 200){
                        $("#lazlfive").before('<div class="layui-upload-list" style="margin:0 10px 5px;">' +
                            '<img class="layui-upload-img" src="/storage/images/'+rs.data.path+'_120x120"/>' +
                            '<p class="file-nme" title="'+rs.data.name+'">'+ rs.data.name +'</p>' +
                            '<p class="msg-box"><a target="_blank" href="/storage/files/'+res.data.path+'" class="layui-btn layui-btn-normal layui-btn-xs">查看</a><a  href="/storage/files/dl/'+res.data.path+'" class="layui-btn layui-btn-normal  layui-btn-xs">下载</a><button  href="/elderlyPth/delete?id='+rs.data.id+'" class="layui-btn layui-btn-normal  layui-btn-xs pthid" type="button">删除</button></p></div>');

                    }else {
                        layer.msg('上传失败');
                    }
                }
            });
        }
    });
    // 上传入住合同
    upload.render({
        elem: '#lazlsix'
        ,url: '/storage/files/ul'
        ,field: 'file'
        ,accept:"images"
        ,acceptMime:"image/jpg,image/jpeg,image/png"
        ,size:5120
        ,done: function(res){
            if(res.code != 200){
                return layer.msg('上传失败');
            }
            $.ajax({
                url:"/elderlyPth/save",
                type:'POST',
                dataType:'JSON',
                data:{elderlyId:$("#id").val(),name:res.data.fileName,path:res.data.path,type:$("#lazlsix").data("type")},
                success:function(rs){
                    if(rs.code == 200){
                        $("#lazlsix").before('<div class="layui-upload-list" style="margin:0 10px 5px;">' +
                            '<img class="layui-upload-img" src="/storage/images/'+rs.data.path+'_120x120"/>' +
                            '<p class="file-nme" title="'+rs.data.name+'">'+ rs.data.name +'</p>' +
                            '<p class="msg-box"><a target="_blank" href="/storage/files/'+res.data.path+'" class="layui-btn layui-btn-normal layui-btn-xs">查看</a><a  href="/storage/files/dl/'+res.data.path+'" class="layui-btn layui-btn-normal  layui-btn-xs">下载</a><button  href="/elderlyPth/delete?id='+rs.data.id+'" class="layui-btn layui-btn-normal  layui-btn-xs pthid" type="button">删除</button></p></div>');

                    }else {
                        layer.msg('上传失败');
                    }
                }
            });
        }
    });
    $("#lezlup").on('click','.pthid',function () {
        $(this).parent().parent().remove();
        $.ajax({
            url:"/elderlyPth/delete",
            type:'POST',
            dataType:'JSON',
            data:{id:$(this).data("pthid")},
            success:function(rs){
                if(rs.code == 200){

                }else {
                    layer.msg('上传失败');
                }
            }
        });
    })

    $("#idNo").blur(function () {
        var idNo = $(this).val();
        var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (reg.test(idNo) === false) {
            layer.msg("请填写正确的身份证号");
            $("#birthday").val("")
        } else {
            if (idNo.length == 15) {
                var s = idNo.substring(0, 6);
                var s1 = idNo.substring(6, 15);
                idNo = s + "19" + s1;
            }
            $("#birthday").val(idNo.substring(6, 10) + "-" + idNo.substring(10, 12) + "-" + idNo.substring(12, 14))
        }

    })
});